import store from "@/store/index.js";
export const init = () => {
  // 重写消息提示框。
  uni.$showMsg = function (title = "", icon = "", duration = 1500) {
    uni.showToast({
      title,
      duration,
      icon: "none",
      position: "bottom",
    });
  };
};

/**
 * 启动初始化
 */
export const initLaunch = async () => {
  // await refreshToken(); //刷新token
  // checkUserState(); //检测用户信息
  initSystem(); //初始化系统配置
  // #ifdef MP-WEIXIN
  // wxLogin(); //微信登录
  // #endif
};

export const initShow = () => {
  onNetworkStatusChange();
};
/**
 * 检测用户信息
 */
export const checkUserState = async () => {
  const token = store.state.token.access_token;
  if (token) {
    //更新用户信息
    await store.dispatch("getUserInfo");
    //获取导师认证状态
    await store.dispatch("getLecturerAuditState");

    //判断用户是否有进行选择身份或完善信息
    const step = store.state.userInfo.step;
    if (step === 0) {
      return uni.reLaunch({ url: `/pages/choiceRole/choiceRole` });
    } else if (step === 1) {
      return uni.reLaunch({ url: `/pages/perfectInfo/perfectInfo` });
    }

    const globalAuth = store.state.globalAuth;
    //1 我是专家 2 我是投资人 3 我是企业 4.我是服务机构
    const globalAuthType = store.getters.globalAuthType;

    //导师认证    0-未审核；1-审核通过；2-审核未通过；3-未认证
    const isTutorAuth = store.state.lecturerStatus;

    /**
     * 导师未认证时直接跳转到认证页
     */
    if (globalAuthType === 1 || globalAuthType === 4) {
      switch (isTutorAuth) {
        case 0:
          uni.reLaunch({ url: "/pagesA/pages/tutorAuthentication/authState" });
          break;
        case 1:
          uni.switchTab({ url: "/pages/conslt/index" });
          break;
        case 2:
          uni.reLaunch({ url: "/pagesA/pages/tutorAuthentication/authState" });
          break;
        case 3:
          uni.reLaunch({ url: "/pagesA/pages/authentication/authentication" });
          break;
        default:
          break;
      }
    } else if (globalAuthType === 2) {
      uni.switchTab({ url: "/pages/specialist/specialist" });
    } else if (globalAuthType === 3) {
      uni.switchTab({ url: "/pages/specialist/specialist" });
    }
  } else {
    uni.reLaunch({ url: "/pages/login/login" });
  }
};

/**
 * 初始化系统配置
 */
const initSystem = () => {
  //布局信息
  let statusBar = 0; //状态栏高度
  let customBar = 0; // 状态栏高度 + 导航栏高度
  let navbar = 0; // 自定义标题与胶囊对齐高度
  let capsuleWidth = 0; //胶囊宽度
  let versionNumber = "v1.0.0";
  let screenHeight = 0; //屏幕宽度
  let screenWidth = 0; //screenWidth
  let osName = "";
  uni.getSystemInfo({
    success: (e) => {
      screenHeight = e.screenHeight;
      screenWidth = e.screenWidth;
      osName = e.osName; //系统名称
      // #ifdef MP-WEIXIN
      statusBar = e.statusBarHeight;
      const custom = wx.getMenuButtonBoundingClientRect();
      customBar = custom.bottom + custom.top - e.statusBarHeight;
      navbar = (custom.top - e.statusBarHeight) * 2 + custom.height;
      capsuleWidth = e.windowWidth - custom.right + custom.width;
      // #endif

      // #ifdef APP-PLUS
      statusBar = e.statusBarHeight;
      customBar = e.statusBarHeight + 45;
      navbar = 45;

      //安卓底部安全区域设置
      if (osName != "ios") {
        const Color = plus.android.importClass("android.graphics.Color");
        plus.android.importClass("android.view.Window");
        const mainActivity = plus.android.runtimeMainActivity();
        const window_android = mainActivity.getWindow();
        window_android.setNavigationBarColor(Color.parseColor("#ebecf1"));
      }
      // #endif

      // #ifdef H5
      statusBar = e.statusBarHeight;
      customBar = e.statusBarHeight + 45;
      navbar = 45;
      // #endif
    },
  });

  //小程序版本号
  // #ifdef MP-WEIXIN
  const accountInfo = wx.getAccountInfoSync();
  versionNumber = accountInfo.miniProgram.version || "v1.0.0"; // 小程序 版本号
  // #endif

  //app版本号
  // #ifdef APP-PLUS
  plus.runtime.getProperty(plus.runtime.appid, (info) => {
    versionNumber = info.version | "v1.0.0";
  });
  // #endif

  store.commit("SET_SYSTEM_CONFIG", {
    statusBar,
    customBar,
    navbar,
    capsuleWidth,
    versionNumber,
    screenHeight,
    screenWidth,
    osName,
  });
};

/**
 * 监听网络变化
 * @param {*} params
 */
function onNetworkStatusChange(params) {
  uni.getNetworkType({
    success: (res) => {
      if (res.networkType == "none") {
        uni.showToast({
          title: "当前无网络连接",
          icon: "none",
          position: "bottom",
        });
      }
    },
  });
  // uni.onNetworkStatusChange(function (res) {
  //   console.log(res.isConnected);
  //   console.log(res.networkType);
  // });
}

/**
 * 使用微信登录
 */
function wxLogin() {
  uni.login({
    provider: "weixin",
    success: function (loginRes) {
      store.dispatch("getOpenId", {
        jsCode: loginRes.code,
      });
    },
  });
}

/**
 * 刷新token
 */
const refreshToken = async () => {
  return new Promise((resolve, reject) => {
    if (store.state && store.state.token && store.state.token.accessTokenDate) {
      const now = new Date().getTime();
      const expiredTime = new Date(store.state.token.accessTokenDate).getTime();
      const refreshTime = new Date(store.state.token.nowDate).getTime();
      //大于最长时间token失效重新登录
      if (expiredTime - now < 0) {
        uni.reLaunch({ url: "/pages/login/login" });
      } else if (expiredTime - now < (expiredTime - refreshTime) / 2) {
        store
          .dispatch("getAccessToken", {
            refresh_token: store.state.token.refresh_token,
          })
          .then((res) => {
            resolve();
          })
          .catch(() => {
            uni.reLaunch({ url: "/pages/login/login" });
          });
      } else {
        resolve();
      }
    } else {
      resolve();
    }
  });
};
